package com.xxl.job.core.thread;

import com.xxl.job.core.log.XxlJobFileAppender;
import com.xxl.job.core.util.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * job file clean thread
 * Job 日志文件清理线程
 * 1. 定制清理产生的Job日志
 * @author xuxueli 2017-12-29 16:23:43
 */
public class JobLogFileCleanThread {
    private static Logger logger = LoggerFactory.getLogger(JobLogFileCleanThread.class);

    private static JobLogFileCleanThread instance = new JobLogFileCleanThread();
    public static JobLogFileCleanThread getInstance(){
        return instance;
    }

    private Thread localThread;

    /**
     * 是否暂停的线程可见标志
     */
    private volatile boolean toStop = false;

    /**
     * 1. 启动线程,如果日志保留小于3天 直接结束
     * 2. 如果没有暂停 线程将每隔1天执行一次,找到保留周期之外的Log日志删除掉
     * @param logRetentionDays
     */
    public void start(final long logRetentionDays){

        // limit min value
        if (logRetentionDays < 3 ) {
            return;
        }

        localThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (!toStop) {
                    try {
                        // clean log dir, over logRetentionDays
                        File[] childDirs = new File(XxlJobFileAppender.getLogPath()).listFiles();
                        if (childDirs!=null && childDirs.length>0) {

                            // today
                            Calendar todayCal = Calendar.getInstance();
                            todayCal.set(Calendar.HOUR_OF_DAY,0);
                            todayCal.set(Calendar.MINUTE,0);
                            todayCal.set(Calendar.SECOND,0);
                            todayCal.set(Calendar.MILLISECOND,0);

                            Date todayDate = todayCal.getTime();

                            for (File childFile: childDirs) {

                                // valid
                                if (!childFile.isDirectory()) {
                                    continue;
                                }
                                if (childFile.getName().indexOf("-") == -1) {
                                    continue;
                                }

                                // file create date
                                Date logFileCreateDate = null;
                                try {
                                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                                    logFileCreateDate = simpleDateFormat.parse(childFile.getName());
                                } catch (ParseException e) {
                                    logger.error(e.getMessage(), e);
                                }
                                if (logFileCreateDate == null) {
                                    continue;
                                }

                                if ((todayDate.getTime()-logFileCreateDate.getTime()) >= logRetentionDays * (24 * 60 * 60 * 1000) ) {
                                    FileUtil.deleteRecursively(childFile);
                                }

                            }
                        }

                    } catch (Exception e) {
                        if (!toStop) {
                            logger.error(e.getMessage(), e);
                        }

                    }

                    try {
                        TimeUnit.DAYS.sleep(1);
                    } catch (InterruptedException e) {
                        // 暂停清理日志会中断此线程并抛出InterruptedException
                        if (!toStop) {
                            logger.error(e.getMessage(), e);
                        }
                    }
                }
                logger.info(">>>>>>>>>>> xxl-job, executor JobLogFileCleanThread thread destroy.");

            }
        });
        localThread.setDaemon(true);
        localThread.setName("xxl-job, executor JobLogFileCleanThread");
        localThread.start();
    }

    /**
     * 暂停清理日志的线程
     * 1. 重置是否暂停信号量
     * 2. 中断sleep的线程
     * 3. 抢占cpu完成暂停后的工作-输出日志
     *
     * 如果线程不是在sleep 而是在清理文件,那么发出中断请求后将不会进行sleep 而是清除中断状态抛出InterruptedException
     * stop使用中断机制可以保证正在执行清除的线程会将本次清理完成
     */
    public void toStop() {
        // 修改暂停标志量
        toStop = true;

        // 保留周期过小 线程不启动
        if (localThread == null) {
            return;
        }

        /**
         * 协商暂停清理日志的线程，回顾下interrupt是暂停线程，实际上属于一种协商机制不会立刻暂停，而是发出中断请求
         * 最大的可能是 线程已经调用了sleep 进入阻塞状态，此时发出中断请求,让出执行立刻抛出异常
         */
        // interrupt and wait
        localThread.interrupt();
        try {
            // 中断请求后立刻join,以触发暂停后的操作
            localThread.join();
        } catch (InterruptedException e) {
            logger.error(e.getMessage(), e);
        }
    }

}
